import { ref, reactive, onMounted, type Ref } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { ResourceItem } from "./type/resourceTypes.ts";
import { h } from "vue";
import resourceForm from "../componentsForm/resourceForm.vue";
import { setOriginalFormName } from "./rule/resourceRules";

export function useResourceTable(
  tableRef: Ref,
  lesseeId: number,
  dealerId: number,
  dealerName: string,
  tenantName: string
) {
  const form = reactive({
    name: "",
    code: "",
    type: "",
    lesseeName: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = ref();
  const dataList = ref<ResourceItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  // 列表列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "资源名称",
      prop: "Name",
      minWidth: 180
    },
    {
      label: "资源编号",
      prop: "Code",
      minWidth: 100
    },
    {
      label: "资源类型",
      prop: "TypeName",
      minWidth: 120
      //slot: "TypeName"
    },
    {
      label: "URL",
      prop: "FileName",
      minWidth: 180
    },
    {
      label: "备注",
      prop: "Comment",
      minWidth: 150
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      tenantId: lesseeId
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/Asset"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items || [];
          pagination.total = res.Data.TotalCount || 0;
          dataList.value.forEach(item => {
            item.TenantName = tenantName;
            item.DealerName = dealerName;
            // 添加类型文本映射
            if (Number(item.Type) === 1) {
              item.TypeName = "普通音频文件";
            } else if (Number(item.Type) === 2) {
              item.TypeName = "TTS";
            } else {
              item.TypeName = "未知类型";
            }
          });
          console.log(dataList.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  // 新增、修改资源
  function openDialog(title: string, row: any = null) {
    const id = row?.Id ?? "";
    const originalName = row?.Name ?? "";
    setOriginalFormName(originalName);
    const formInlineData = {
      id: row?.Id ?? 0,
      dealerId: row?.DealerId ?? 0,
      tenantId: row?.TenantId ?? 0,
      name: row?.Name ?? "",
      code: row?.Code ?? 0,
      type: row?.Type ?? 1,
      comment: row?.Comment ?? "",
      fileId: row?.FileId ?? 0,
      //fileName: row?.FileName ?? "",
      fileSize: row?.FileSize ?? 0,
      fileKey: row?.FileName ?? ""
    };
    addDialog({
      title: `${title}资源`,
      props: {
        formInline: formInlineData,
        title: title
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(resourceForm, {
          ref: formRef,
          formInline: formInlineData,
          title: title
        }),

      beforeSure: (done, { options: _options }) => {
        const FormRef = formRef.value.getRef();
        const curData = formRef.value.getFormData();
        console.log("上传文件参数", curData);
        function chores() {
          message(`您${title}了资源ID为【${curData.id}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData,
              tenantId: lesseeId,
              dealerId: dealerId
            };
            console.log(formData);
            if (title === "创建") {
              http
                .post(changeHttpLink("/api/Asset"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/Asset/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除资源
  function handleDelete(row: ResourceItem) {
    ElMessageBox.confirm(
      `是否确认删除资源ID为${row.Id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .request("delete", changeHttpLink(`/api/Asset/${row.Id}`), {
            data: row.Id
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`您删除了资源ID为${row.Id}的这条数据`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Asset/batch-delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: ResourceItem[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }

  onMounted(() => {
    onSearch();
  });
  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
